package com.lilingguo.easyserver.controller;

import com.lilingguo.easyserver.container.Container;
import com.lilingguo.easyserver.pojo.Monitor;
import com.lilingguo.easyserver.pojo.ServiceInfo;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * 服务治理相关
 *
 * @Author: 黎铃果
 * @Date: 2020/05/28 16:37
 */
@Log4j2
@RestController
@RequestMapping("/easyserver")
public class EasyServerController {

    @Autowired
    private Container container;

    @Autowired
    private Monitor monitor;

    @PostMapping("/register")
    public String register(@RequestBody ServiceInfo info) {
        // ignore case sensitive
        String upperCaseName = info.getName().toUpperCase();
        info.setName(upperCaseName);
        boolean result = container.saveInfo(info);
        String status = ServiceInfo.ERROR;
        if (result) {
            status = ServiceInfo.OK;
        }
        log.debug("register [" + status + "] -> " + info.getIdStr());
        return status;
    }

    @GetMapping("/getServiceList")
    public Set<ServiceInfo> getServerList(@RequestParam String appName) {
        return container.getInfo(appName);
    }

    @DeleteMapping("/close")
    public String close(@RequestBody ServiceInfo info) {
        log.info("service closed forwardly -> " + info.getIdStr());
        boolean result = container.removeInfo(info);
        if (result) {
            return ServiceInfo.OK;
        }
        return ServiceInfo.ERROR;
    }

    @PostMapping("/heartBeat")
    public String tick(@RequestBody ServiceInfo info) {
        boolean result = container.keepAlive(info);
        if (result) {
            // tick count
            monitor.setTickCount(monitor.getTickCount() + 1);
            return ServiceInfo.OK;
        }
        return ServiceInfo.ERROR;
    }

}
